package com.blakequ.androidblemanager;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.RemoteException;
import android.util.Log;

import com.blakequ.androidblemanager.ui.MainPage;
import com.blakequ.androidblemanager.utils.CrashHandler;
import com.blakequ.bluetooth_manager_lib.scan.BackgroundPowerSaver;
import com.tamsiree.rxkit.RxTool;
import com.tencent.mmkv.MMKV;

import org.altbeacon.beacon.BeaconManager;
import org.altbeacon.beacon.BeaconParser;
import org.altbeacon.beacon.MonitorNotifier;
import org.altbeacon.beacon.Region;
import org.altbeacon.beacon.startup.RegionBootstrap;

/**
 * 支持LitePal数据库
 * Created by xiachao on 2020.
 */

public class MyApplication extends Application implements MonitorNotifier {
    private static final String TAG = "BeaconReferenceApp";
    private static Context context;

    private static MyApplication instance;

    @Override
    public void onCreate() {
        super.onCreate();
        RxTool.init(this);
        context = getApplicationContext();
        instance = this;
        MMKV.initialize(this);
        CrashHandler.getInstance().init(this,"/BLE/log/");
        initNewBle();
    }


    private void initNewBle() {
        BeaconManager beaconManager = BeaconManager.getInstanceForApplication(this);
        // To detect proprietary beacons, you must add a line like below corresponding to your beacon
        // type.  Do a web search for "setBeaconLayout" to get the proper expression.
        beaconManager.getBeaconParsers().clear();
         beaconManager.getBeaconParsers().add(new BeaconParser().
//                setBeaconLayout("m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25"));
        setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"));



        // wake up the app when any beacon is seen (you can specify specific id filers in the parameters below)
        Region region = new Region("com.example.myapp.boostrapRegion", null, null, null);
        try {
            BeaconManager.getInstanceForApplication(this).startMonitoringBeaconsInRegion(region);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        BeaconManager.getInstanceForApplication(this).addMonitorNotifier(this);
    }

    //初始化蓝牙
    private void initBle() {
//        Ble.options()
//                .setLogBleEnable(true)//设置是否输出打印蓝牙日志
//                .setThrowBleException(true)//设置是否抛出蓝牙异常
//                .setLogTAG(TAGBLE)//设置全局蓝牙操作日志TAG
//                .setAutoConnect(true)//设置是否自动连接
//                .setIgnoreRepeat(false)//设置是否过滤扫描到的设备(已扫描到的不会再次扫描)
//                .setConnectFailedRetryCount(3)//连接异常时（如蓝牙协议栈错误）,重新连接次数
//                .setConnectTimeout(10 * 1000)//设置连接超时时长
//                .setScanPeriod(12 * 1000)//设置扫描时长
//                .setMaxConnectNum(7)//最大连接数量
//                .setUuidService(UUID.fromString(UuidUtils.uuid16To128("ff10")))//设置主服务的uuid
//                .setUuidWriteCha(UUID.fromString(UuidUtils.uuid16To128("ff11")))//设置可写特征的uuid
//                .setUuidReadCha(UUID.fromString(UuidUtils.uuid16To128("ff12")))//设置可读特征的uuid （选填）
//                .setUuidNotifyCha(UUID.fromString(UuidUtils.uuid16To128("ff12")))//设置可通知特征的uuid （选填，库中默认已匹配可通知特征的uuid）
//                .setFactory(new BleFactory<BleRssiDevice>() {//实现自定义BleDevice时必须设置
//                    @Override
//                    public BleRssiDevice create(String address, String name) {
//                        return new BleRssiDevice(address, name);//自定义BleDevice的子类
//                    }
//                })
//                .setBleWrapperCallback(new MyBleWrapperCallback())
//                .create(this, new Ble.InitCallback() {
//                    @Override
//                    public void success() {
//                        BleLog.e("MainApplication", "初始化成功");
//                    }
//
//                    @Override
//                    public void failed(int failedCode) {
//                        BleLog.e("MainApplication", "初始化失败：" + failedCode);
//                    }
//                });
    }


    public static Context getAppContext() {
        return context;
    }

    public static MyApplication getInstance() {
        return instance;
    }



    @Override
    public void didDetermineStateForRegion(int arg0, Region arg1) {
        // Don't care
    }

    @Override
    public void didEnterRegion(Region arg0) {
        Log.d(TAG, "Got a didEnterRegion call");
        // This call to disable will make it so the activity below only gets launched the first time a beacon is seen (until the next time the app is launched)
        // if you want the Activity to launch every single time beacons come into view, remove this call.
        Region region = new Region("com.example.myapp.boostrapRegion", null, null, null);
        try {
            BeaconManager.getInstanceForApplication(this).stopMonitoringBeaconsInRegion(region);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        Intent intent = new Intent(this, MainPage.class);
        // IMPORTANT: in the AndroidManifest.xml definition of this activity, you must set android:launchMode="singleInstance" or you will get two instances
        // created when a user launches the activity manually and it gets launched from here.
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        this.startActivity(intent);
    }

    @Override
    public void didExitRegion(Region arg0) {
        // Don't care
    }
}
